package com.sec.android.app.myfiles.fragment.filelist;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Pair;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toolbar;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.CopyMoveCmd.OperationProgress;
import com.sec.android.app.myfiles.facade.cmd.CreateDocumentCmd;
import com.sec.android.app.myfiles.facade.cmd.FinishPickerCmd;
import com.sec.android.app.myfiles.feature.layout.split.SplitLayoutManager;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment.ActionModeType;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.ModuleLoader;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.module.abstraction.IMenuImp;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationInfo.NavigationMode;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperator.Operation;
import com.sec.android.app.myfiles.util.CreateDocumentTask;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.HashMap;

public class FileListActionMenu {
    private final Context mContext;
    private final HashMap<StorageType, IMenuImp> mMenuImpMap;
    private IMenuImp mMenuImp;

    private AbsMyFilesFragment mFragment;
    private ActionModeType mActionModeType;
    private NavigationInfo mNavigationInfo;

    private TextView mActionBar_Title;
    private TextView mActionBar_Cancel;
    private TextView mActionBar_Done;
    private TextView mSelectedCounter;
    private RelativeLayout mSelectAllCheckboxContainer;
    private CheckBox mSelectAllCheckbox;

    private Menu mMenuInstance;
    private int mActionBarAppNameWidth;
    private View mSelectAllDivider;
    private int mSelectAllDividerWidth;
    private TextView mActionBarAppName;
    private RelativeLayout mActionBar;
    private SplitLayoutManager mSplitLayoutMgr;

    public FileListActionMenu(Context context, NavigationInfo navigationInfo, AbsMyFilesFragment fragment) {
        mContext = context;
        mFragment = fragment;
        mNavigationInfo = navigationInfo;
        mMenuImpMap = new HashMap<>();
    }

    public void setInfo(AbsMyFilesFragment fragment, NavigationInfo navigationInfo) {
        mFragment = fragment;
        mNavigationInfo = navigationInfo;
        createMenuImp();
        if (mMenuImp != null) {
            mMenuImp.setInfo(fragment, navigationInfo);
        }
    }

    private IMenuImp getMenuImp(StorageType storageType) {
        IMenuImp menuImp = mMenuImpMap.get(storageType);
        if (menuImp == null) {
            menuImp = ModuleLoader.getInstance().createMenuImp(mContext, storageType);
            mMenuImpMap.put(storageType, menuImp);
        }
        return menuImp;
    }

    private void createMenuImp() {
        if (mNavigationInfo != null) {
            if (mMenuImp != null) {
                mMenuImp.setInfo(null, null);
            }
            StorageType storageType = mNavigationInfo.getStorageType();
            mMenuImp = getMenuImp(storageType);
        }
    }

    public void onCreateOptionsMenu(ActionMode mode, Menu menu, MenuInflater inflater, ActionModeType actionMode) {
        switch (actionMode) {
            case SELECT_FILE_FOLDER_OPERATION:
            case EDIT_FILE_FOLDER_OPERATION:
            case SELECT_SHARE_FILE_OPERATION:
                initSelectLayout(mode);
                break;
            default:
                break;
        }

        if (mMenuImp != null) {
            mMenuImp.onCreateOptionsMenu(menu, inflater, actionMode);
        }
        mMenuInstance = menu;
    }

    public Menu getMenuInstance() {
        return mMenuInstance;
    }

    @SuppressLint("InflateParams")
    private View createSelectActionBarLayout() {
        View ret = LayoutInflater.from(mContext).inflate(R.layout.actionbar_select_all, null);
        mActionBar = (RelativeLayout) ret;
        mSelectAllCheckboxContainer = (RelativeLayout) ret.findViewById(R.id.actionbar_select_all_container);
        mSelectAllCheckbox = (CheckBox) ret.findViewById(R.id.actionbar_select_checkbox);
        mSelectedCounter = (TextView) ret.findViewById(R.id.actionbar_select_count);
        UiUtils.limitLargeTextSize(mContext, mSelectedCounter);
        mActionBarAppName = (TextView) ret.findViewById(R.id.app_title);
        mSelectAllDivider = ret.findViewById(R.id.action_bar_split_divider);

        initSelectAllDivider();
        initSelectAllCheckboxContainer();
        return ret;
    }

    private void initSelectAllDivider() {
        if (AppFeatures.isTabletUIMode()) {
            mSplitLayoutMgr = SplitLayoutManager.getInstance(mFragment.getProcessId());
            mActionBarAppName.setVisibility(View.VISIBLE);
            mSelectAllDivider.setVisibility(View.VISIBLE);
            UiUtils.limitLargeTextSize(mContext, mActionBarAppName);

            Drawable divider = mContext.getResources().getDrawable(R.drawable.split_view_divider_line, null);
            if (divider != null) {
                divider.setAutoMirrored(true);
                mSelectAllDivider.setBackground(divider);
            }

            mActionBarAppName.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            mActionBarAppNameWidth = mActionBarAppName.getMeasuredWidth();
            mSelectAllDividerWidth = mContext.getResources().getDimensionPixelOffset(R.dimen.split_view_divider_width);
            updateSelectAllStartMargin();
        } else {
            mActionBarAppName.setVisibility(View.GONE);
            mSelectAllDivider.setVisibility(View.GONE);
        }
    }

    private void initSelectAllCheckboxContainer() {
        if (mSelectAllCheckboxContainer != null) {
            mSelectAllCheckboxContainer.setEnabled(mFragment.getTotalCheckableFileCount() > 0);
            mSelectAllCheckboxContainer.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isChecked = !mSelectAllCheckbox.isChecked();
                    mSelectAllCheckbox.setChecked(isChecked);
                    try {
                        String onClickDescription = isChecked ? mFragment.getResources().getString(R.string.tts_actionbar_selected) : mFragment.getResources().getString(R.string.tts_actionbar_not_selected);
                        AccessibilityManager manager = (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
                        if (manager != null && manager.isEnabled()) {
                            AccessibilityEvent e = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT);
                            e.getText().clear();
                            e.getText().add(onClickDescription);
                            manager.sendAccessibilityEvent(e);
                        }
                        int selectedCount = (isChecked) ? mFragment.getTotalCheckableFileCount() : 0;
                        setContentDescription(selectedCount, -1);
                        mFragment.selectAll(isChecked);
                        mFragment.updateActionBarMenu();
                    } catch (IllegalStateException e) {
                        Log.d(this, "FileListFragment is not attached to Activity");
                    }
                }
            });
        }
    }

    private void initSelectLayout(ActionMode mode) {
        if (mode == null) {
            return;
        }
        View actionBarLayout = createSelectActionBarLayout();
        mode.setCustomView(actionBarLayout);
        setContentDescription(mFragment.getSelectedFileCount(), -1);
    }

    public void updateSelectAllCheckboxContainer() {
        if (mSelectAllCheckboxContainer != null) {
            mSelectAllCheckboxContainer.setPadding(mSelectAllCheckboxContainer.getPaddingStart(), (int) mSelectAllCheckboxContainer.getResources().getDimension(R.dimen.actionbar_select_checkbox_padding_top), mSelectAllCheckboxContainer.getPaddingEnd(), mSelectAllCheckboxContainer.getPaddingBottom());
        }
    }

    public void updateSelectAllDivider(boolean isPressed) {
        ViewGroup.LayoutParams params = mSelectAllDivider.getLayoutParams();
        if (isPressed) {
            params.width = (int) mContext.getResources().getDimension(R.dimen.split_view_divider_width_pressed);
        } else {
            params.width = (int) mContext.getResources().getDimension(R.dimen.split_view_divider_width);
        }
        mSelectAllDividerWidth = params.width;
        mSelectAllDivider.setLayoutParams(params);
        mSelectAllDivider.setPressed(isPressed);
    }

    public void updateSelectAllStartMargin() {
        if (mSplitLayoutMgr != null) {
            int selectAllDividerStartMargin = mSplitLayoutMgr.getLeftContainerWidth() - mSelectAllDividerWidth;
            updateSelectAllDividerMargin(selectAllDividerStartMargin);
            updateActionBarAppNameWidth(selectAllDividerStartMargin);

            int actionBarWidth = mActionBar.isShown() ? mActionBar.getWidth() : 0;
            if (mFragment.isSelectActionMode() || (mNavigationInfo != null && mNavigationInfo.isSelectMode())) {
                mSelectedCounter.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                mSelectAllCheckboxContainer.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                int selectAllWidth = mSelectedCounter.getRight() - mSelectAllCheckboxContainer.getLeft();
                if (actionBarWidth > 0 && selectAllWidth > 0) {
                    mSplitLayoutMgr.setActionBarMaxWidth(actionBarWidth - selectAllWidth);
                }
            } else {
                mSplitLayoutMgr.setActionBarMaxWidth(actionBarWidth);
            }
        }
    }

    private void updateSelectAllDividerMargin(int selectAllDividerStartMargin) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mSelectAllDivider.getLayoutParams();
        if (UiUtils.isInRTLMode(mContext)) {
            lp.setMargins(lp.leftMargin, lp.topMargin, selectAllDividerStartMargin, lp.bottomMargin);
        } else {
            lp.setMargins(selectAllDividerStartMargin, lp.topMargin, lp.rightMargin, lp.bottomMargin);
        }
        mSelectAllDivider.setLayoutParams(lp);
    }

    private void updateActionBarAppNameWidth(int selectAllDividerStartMargin) {
        if (selectAllDividerStartMargin < mActionBarAppNameWidth) {
            mActionBarAppName.setWidth(selectAllDividerStartMargin);
        } else {
            mActionBarAppName.setWidth(mActionBarAppNameWidth);
        }
    }

    public void updateSelectedItemView() {
        if (mFragment != null) {
            int nSelectedCnt = mFragment.getSelectedFileCount();
            setContentDescription(nSelectedCnt, -1);

            NavigationInfo navigationInfo = mFragment.getNavigationInfo();
            boolean isSelectMode = navigationInfo != null && navigationInfo.isSelectMode();
            if (mSelectedCounter != null && (mFragment.getActionModeType() != ActionModeType.NORMAL || isSelectMode)) {
                String countMsg = mMenuImp.getSelectedItemString(nSelectedCnt);
                mSelectedCounter.setText(countMsg);
                if (AppFeatures.isTabletUIMode()) {
                    updateSelectAllStartMargin();
                }
            }

            int totalCnt = mFragment.getTotalCheckableFileCount();

            if (mSelectAllCheckboxContainer != null) {
                if (mSelectedCounter != null) {
                    boolean isEnabled = (totalCnt > 0);
                    mSelectAllCheckboxContainer.setEnabled(isEnabled);
                    mSelectedCounter.setEnabled(isEnabled);
                }
                if ((nSelectedCnt > 0 && nSelectedCnt == totalCnt) || (mNavigationInfo.isPickerMode() && nSelectedCnt == mNavigationInfo.getMaxSelectCnt())) {
                    mSelectAllCheckbox.setChecked(true);
                } else {
                    mSelectAllCheckbox.setChecked(false);
                }
            }
            setEnableActionBar_Done();
            updateSelectLayoutMenu();
        }
    }

    public void onPrepareOptionsMenu(Menu menu) {
        if (mMenuImp != null) {
            mMenuImp.onPrepareOptionsMenu(menu, mActionModeType);
        }

        if (mNavigationInfo != null && mNavigationInfo.getNavigationMode() != NavigationMode.Normal) {
            updateSelectedItemView();
        }
    }

    private void updateSelectLayoutMenu() {
        if (mMenuInstance != null && mNavigationInfo != null) {
            mMenuImp.onUpdateSelectLayoutMenu(mMenuInstance, mNavigationInfo);
        }
    }

    public void onPrepareActionMenu(Menu menu, ActionModeType actionMode) {
        if (mMenuImp != null) {
            mMenuImp.onPrepareActionMenu(menu, actionMode);
        }

        updateSelectedItemView();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        boolean bRet = false;
        if (mMenuImp != null) {
            bRet = mMenuImp.onOptionsItemSelected(item);
        }
        return bRet;
    }

    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        boolean bRet = false;
        if (mMenuImp != null) {
            bRet = mMenuImp.onActivityResult(requestCode, resultCode, data);
        }
        return bRet;
    }

    public ActionMode setActionBar(Activity activity, ActionModeType actionModeType, AbsMyFilesFragment fragment) {
        ActionMode ret = null;
        if (activity != null) {
            if (mNavigationInfo != null) {
                mActionModeType = actionModeType;
                restoreActionBarInset(activity.getActionBar());
                NavigationMode navigationMode = mNavigationInfo.getNavigationMode();

                switch (navigationMode) {
                    case Select_copy_destination:
                    case Select_move_destination:
                    case Select_remove_from_private:
                    case Select_optimize_storage_backup_destination:
                        setActionBarSelectCopyMoveDst(activity, navigationMode);
                        break;
                    case Select_destination_path:
                        setActionBarSelectPathDst(activity, navigationMode);
                        break;
                    case Select_create_doc_destination:
                        setActionBarCreateDoc(activity, navigationMode);
                        break;
                    case Pick_one_file:
                        setActionBarPickOneFile(activity, navigationMode);
                        break;
                    case Pick_files:
                        setActionBarPickFiles(activity);
                        break;
                    case Optimize_storage_files:
                    case Preview_compress_item:
                        setActionBarPreviewCompress(activity);
                        break;
                    default:
                        if (mActionModeType == ActionModeType.SELECT_FILE_FOLDER_OPERATION
                                || mActionModeType == ActionModeType.EDIT_FILE_FOLDER_OPERATION
                                || mActionModeType == ActionModeType.SELECT_SHARE_FILE_OPERATION) {
                            if (fragment != null)
                                ret = activity.startActionMode(fragment);
                        } else {
                            setActionBarNormal(activity.getActionBar());
                        }
                        break;
                }
            }
        }

        return ret;
    }

    private void setActionBarNormal(ActionBar actionbar) {
        if (mMenuImp != null && actionbar != null) {
            restoreActionBarInset(actionbar);
            mMenuImp.setActionBarNormal(actionbar);
        }
    }

    private View createDone_CancelActionBarLayout() {
        int actionbarLayoutId = R.layout.action_bar_pick_single_done;
        if (mNavigationInfo.isSelectOpDestination() || mNavigationInfo.isCreateDocument()) {
            actionbarLayoutId = R.layout.action_bar_op_cancel_done;
        }

        View ret = LayoutInflater.from(mContext).inflate(actionbarLayoutId, null);

        if (ret != null) {
            mActionBar_Title = (TextView) ret.findViewById(R.id.actionbar_title);
            UiUtils.limitLargeTextSize(mContext, mActionBar_Title);

            if (mNavigationInfo.isSelectOpDestination() || mNavigationInfo.isCreateDocument()) {
                mActionBar_Cancel = (TextView) ret.findViewById(R.id.left_btn);
                UiUtils.limitLargeTextSize(mContext, mActionBar_Cancel);
                UiUtils.setBtnBackgroundColor(mContext, mActionBar_Cancel);
            }
            mActionBar_Done = (TextView) ret.findViewById(R.id.right_btn);
            UiUtils.limitLargeTextSize(mContext, mActionBar_Done);
            UiUtils.setBtnBackgroundColor(mContext, mActionBar_Done);
        }

        return ret;
    }

    private void setActionBar_Done_Cancel(Activity activity, String doneText, String doneDescription, OnClickListener doneListener,
                                          OnClickListener cancelListener, NavigationMode navigationMode) {
        View customView = createDone_CancelActionBarLayout();
        ActionBar actionbar = activity.getActionBar();

        if (customView != null && actionbar != null) {
            actionbar.setDisplayHomeAsUpEnabled(false);
            actionbar.setDisplayShowTitleEnabled(false);
            actionbar.setDisplayShowCustomEnabled(true);
            actionbar.setCustomView(customView);

            if (mNavigationInfo.isSelectOpDestination() || mNavigationInfo.isCreateDocument()) {
                setActionBarOpTitle(navigationMode);
                if (cancelListener != null) {
                    mActionBar_Cancel.setContentDescription(mContext.getString(R.string.cancel) + " " + mContext.getString(R.string.button));
                    mActionBar_Cancel.setOnClickListener(cancelListener);
                }
            } else if (mNavigationInfo.isSinglePickerMode() || mNavigationInfo.isSelectDestinationPath()) {
                setActionBarPickOneFileTitle(navigationMode);
            }

            mActionBar_Done.setText(doneText);
            mActionBar_Done.setContentDescription(doneDescription);
            setEnableActionBar_Done();
            mActionBar_Done.setOnClickListener(doneListener);
        }
    }

    private void setEnableActionBar_Done() {
        if (mNavigationInfo != null) {
            if (mActionBar_Done != null) {
                if (mNavigationInfo.getStorageType() == StorageType.Home) {
                    mActionBar_Done.setEnabled(false);
                } else if (mNavigationInfo.isPickerMode()) {
                    mActionBar_Done.setEnabled((mFragment != null) && (mFragment.getSelectedFileCount() > 0));
                } else {
                    mActionBar_Done.setEnabled(true);
                }
            }
        }
    }

    private void setActionBarOpTitle(NavigationMode navigationMode) {
        String title = "";
        switch (navigationMode) {
            case Select_copy_destination:
                title = mContext.getString(R.string.copy_to);
                break;
            case Select_move_destination:
            case Select_remove_from_private:
                title = mContext.getString(R.string.move_to);
                break;
            case Select_destination_path:
            case Select_create_doc_destination:
                title = mContext.getString(R.string.save_to);
                break;
            case Select_optimize_storage_backup_destination:
                title = mContext.getString(R.string.backup_to);
                break;
            default:
                break;
        }
        mActionBar_Title.setText(title);
    }

    private void setActionBarPickOneFileTitle(NavigationMode navigationMode) {
        String title = "";
        switch (navigationMode) {
            case Pick_one_file:
                title = mContext.getString(R.string.select_one_file);
                if (mNavigationInfo.isSingleAudioPickerMode()) {
                    title = mContext.getString(R.string.select_one_audio);
                }
                break;
            case Select_destination_path:
                title = mContext.getString(R.string.select_one_folder);
                break;
            default:
                break;
        }
        mActionBar_Title.setText(title);
    }

    private void setActionBarPickFiles(Activity activity) {
        View customView = createSelectActionBarLayout();

        if (customView != null) {
            ActionBar actionbar = activity.getActionBar();
            if (actionbar != null) {
                actionbar.setDisplayHomeAsUpEnabled(false);
                actionbar.setDisplayShowTitleEnabled(false);
                actionbar.setDisplayShowCustomEnabled(true);
                actionbar.setCustomView(customView);
                removeActionBarInset(actionbar);
            }
        }
    }

    private void setActionBarDone(Activity activity, NavigationMode navigationMode) {
        String doneText = mContext.getString(R.string.menu_done);
        String doneDescription = doneText + ", " + mContext.getString(R.string.button);

        OnClickListener onDone = new OnClickListener() {
            @Override
            public void onClick(View v) {
                SamsungAnalyticsLog.sendLog(mFragment.getProcessId(), SamsungAnalyticsLog.Event.DONE, null);
                MyFilesFacade.finishPicker(mFragment.getProcessId(), mFragment, mNavigationInfo, FinishPickerCmd.PickerCmd.Done);
            }
        };

        setActionBar_Done_Cancel(activity, doneText, doneDescription, onDone, null, navigationMode);
    }

    private void setActionBarPickOneFile(Activity activity, NavigationMode navigationMode) {
        setActionBarDone(activity, navigationMode);
    }

    private void setActionBarSelectPathDst(Activity activity, NavigationMode navigationMode) {
        setActionBarDone(activity, navigationMode);
    }

    private void setActionBarCreateDoc(final Activity activity, NavigationMode navigationMode) {
        String doneText = mContext.getString(R.string.menu_done);
        String doneDescription = doneText + ", " + mContext.getString(R.string.button);

        OnClickListener onCancel = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFragment != null) {
                    Log.d(this, "CreateDocument - Cancel");
                    MyFilesFacade.finishPicker(mFragment.getProcessId(), mFragment, mNavigationInfo, FinishPickerCmd.PickerCmd.Cancel);
                }
            }
        };

        OnClickListener onDone = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(this, "CreateDocument - Done");
                CreateDocumentTask task = new CreateDocumentTask(activity, mNavigationInfo, CreateDocumentCmd.getMimeType(),
                        CreateDocumentCmd.getName(), CreateDocumentCmd.getExtension());
                task.execute();
            }
        };

        setActionBar_Done_Cancel(activity, doneText, doneDescription, onDone, onCancel, navigationMode);
    }

    private void setActionBarSelectCopyMoveDst(Activity activity, NavigationMode navigationMode) {
        String doneText = mContext.getString(R.string.menu_done);
        String doneDescription = doneText + ", " + mContext.getString(R.string.button);

        OnClickListener onCancel = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFragment != null) {
                    NavigationManager.getInstance(mFragment.getProcessId()).backCurNavigationMode();
                    NavigationManager.getInstance(mFragment.getProcessId()).setFromPrivateStorage(false);
                    setActionBarNormal(mFragment.getActivity().getActionBar());
                }
            }
        };

        OnClickListener onDone = new OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopyMove();
            }
        };

        setActionBar_Done_Cancel(activity, doneText, doneDescription, onDone, onCancel, navigationMode);
    }

    private void setActionBarPreviewCompress(Activity activity) {
        View customView = createSelectActionBarLayout();

        if (customView != null) {
            ActionBar actionbar = activity.getActionBar();
            if (actionbar != null) {
                actionbar.setDisplayHomeAsUpEnabled(false);
                actionbar.setDisplayShowCustomEnabled(true);
                actionbar.setDisplayShowTitleEnabled(false);
                actionbar.setCustomView(customView);
                removeActionBarInset(actionbar);
            }
        }
    }

    private void removeActionBarInset(ActionBar actionBar) {
        View customView = actionBar.getCustomView();
        if (customView != null) {
            ViewParent parent = customView.getParent();
            if (parent != null) {
                if (parent instanceof Toolbar) {
                    Toolbar tb = (Toolbar) parent;
                    Pair<Integer, Integer> inset = new Pair<>(tb.getContentInsetStart(), tb.getContentInsetEnd());
                    customView.setTag(inset);
                    tb.setContentInsetsRelative(0, 0);
                }
            }
        }
    }

    private void restoreActionBarInset(ActionBar actionBar) {
        if (actionBar != null) {
            View customView = actionBar.getCustomView();
            if (customView != null) {
                Object insetRaw = customView.getTag();
                if (insetRaw != null) {
                    ViewParent parent = customView.getParent();
                    if (parent != null) {
                        if (parent instanceof Toolbar) {
                            @SuppressWarnings("unchecked")
                            Pair<Integer, Integer> inset = (Pair<Integer, Integer>) insetRaw;
                            Toolbar tb = (Toolbar) parent;
                            tb.setContentInsetsRelative(inset.first, inset.second);
                        }
                    }
                }
            }
        }
    }

    private void doCopyMove() {
        if (mFragment != null) {
            Operation op = Operation.NONE;

            NavigationMode navigationMode = mNavigationInfo.getNavigationMode();

            switch (navigationMode) {
                case Select_copy_destination:
                case Select_optimize_storage_backup_destination:
                    op = Operation.COPY;
                    break;
                case Select_remove_from_private:
                case Select_move_destination:
                    op = Operation.MOVE;
                    break;
                default:
                    break;
            }
            MyFilesFacade.copymoveRecord(mFragment.getProcessId(), mContext, op, OperationProgress.DO_OPERATE, mFragment, null, null);
        }
    }

    private void setContentDescription(int checkedItemCount, int validItemCount) {
        String contentDescription = null;
        if (mSelectAllCheckboxContainer == null)
            return;
        if (validItemCount == -1) {
            validItemCount = mFragment.getTotalCheckableFileCount();
        }
        try {
            if (checkedItemCount == 0) {
                contentDescription = mFragment.getResources().getString(R.string.tts_nothing_selected) + ", "
                        + mFragment.getResources().getString(R.string.tts_double_tap_select_all) + ", "
                        + mFragment.getResources().getString(R.string.tts_tick_box_t_tts) + ", "
                        + mFragment.getResources().getString(R.string.tts_not_ticked_t_tts);
            } else if (checkedItemCount >= 0 && checkedItemCount != validItemCount) {
                contentDescription = mFragment.getResources().getString(R.string.tts_selected, checkedItemCount) + ", "
                        + mFragment.getResources().getString(R.string.tts_double_tap_select_all) + ", "
                        + mFragment.getResources().getString(R.string.tts_tick_box_t_tts) + ", "
                        + mFragment.getResources().getString(R.string.tts_not_ticked_t_tts);
            } else if (checkedItemCount == validItemCount) {
                contentDescription = mFragment.getResources().getString(R.string.tts_selected, checkedItemCount) + ", "
                        + mFragment.getResources().getString(R.string.tts_double_tap_deselect_all) + ", "
                        + mFragment.getResources().getString(R.string.tts_tick_box_t_tts) + ", "
                        + mFragment.getResources().getString(R.string.tts_ticked_t_tts);
            }
        } catch (IllegalStateException e) {
            Log.e(this, e.getMessage());
        }
        if (contentDescription != null) {
            mSelectAllCheckboxContainer.setContentDescription(contentDescription);
        }
    }

    public void onPause() {
        if (mMenuImp != null) {
            mMenuImp.onPause();
        }
    }

    public AbsMyFilesFragment getFragment() {
        return mFragment;
    }

    public void onCreateContextualMenu(ContextMenu menu, AbsMyFilesFragment fragment, FileRecord record) {
        StorageType storageType = record.getStorageType();
        StorageType fragmentStorageType = fragment.getStorageType();
        if (storageType != fragmentStorageType && fragmentStorageType != StorageType.None) {
            storageType = fragmentStorageType;
        }
        IMenuImp menuImp = getMenuImp(storageType);
        if (menuImp != null) {
            menuImp.onCreateContextualMenu(menu, fragment, record);
        }
    }

    public void onContextualItemSelected(MenuItem item, AbsMyFilesFragment fragment, FileRecord record) {
        IMenuImp menuImp = getMenuImp(record.getStorageType());
        if (menuImp != null) {
            menuImp.onContextualItemSelected(item, fragment, record);
        }
    }
}
